﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Reflection;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;

namespace FileManager_Server.Utility.ObjectContainers.Unity
{
    public class UnityObjectContainer : IObjectContainer
    {
        #region Private Fields
        private readonly IUnityContainer container;
        #endregion
        public UnityObjectContainer()
        {
            container = new UnityContainer();
        }
        public T GetService<T>()
        {
            return container.Resolve<T>();
        }

        public object GetService(Type serviceType, object overridedArguments)
        {
            var overrides = new List<ParameterOverride>();
            var argumentsType = overridedArguments.GetType();
            argumentsType.GetProperties(BindingFlags.Public | BindingFlags.Instance)
                .ToList()
                .ForEach(property =>
                {
                    var propertyValue = property.GetValue(overridedArguments, null);
                    var propertyName = property.Name;
                    overrides.Add(new ParameterOverride(propertyName, propertyValue));
                });
            return container.Resolve(serviceType, overrides.ToArray());
        }
        public Array ResolveAll(Type serviceType)
        {
            return container.ResolveAll(serviceType).ToArray();
        }
        public T[] ResolveAll<T>()
        {
            return container.ResolveAll<T>().ToArray();
        }
        public object GetService(Type serviceType)
        {
            return container.Resolve(serviceType);
        }
        public void RegisterType<TIt, T>() where T : TIt
        {
            container.RegisterType<TIt, T>();
        }
        public T GetInterfaceService<T>()
        {
            return container.Resolve<T>();
        }
        public T GetWrappedContainer<T>()
        {
            if (typeof(T).Equals(typeof(UnityContainer)))
                return (T)this.container;
            return default(T);
        }

        public void Initialize()
        {
        }
        public void InitializeFromConfigFile()
        {
            var section = (UnityConfigurationSection)ConfigurationManager.GetSection(UnityConfigurationSection.SectionName);
            section.Configure(container);
        }
    }
}